<?php

	class CSVReader {
	
		const MD5_LENGTH	= 32;
		
		private $csvFile;
		private $arrConfig;
		private $arrHeader;
		private $useMD5;
		private $delimiter;
		
		private $buffer;
		private $strMD5;
		
		public function __construct($csvFile, $arrConfig, $arrHeader = false, $useMD5 = true, $delimiter = '|') {
			$this->csvFile 		= $csvFile;
			$this->arrConfig	= $arrConfig;
			$this->arrHeader	= $arrHeader;
			$this->useMD5 		= $useMD5;
			$this->delimiter	= $delimiter;
			$this->strMD5 		= '';
		}		
		
		public function getArray() {
			$this->buffer = file_get_contents($this->csvFile);
			
			if ($this->buffer === false)
				return null;
				
			$this->buffer = trim($this->buffer);
				
			if ($this->useMD5) {
				$this->strMD5 = substr($this->buffer, (self::MD5_LENGTH * (-1)));
				$this->buffer = substr($this->buffer, 0, (self::MD5_LENGTH * (-1)));
				
				// Verification.
				if (md5($this->buffer) != $this->strMD5)
					return null;
			}
			
			$arrBufLine = explode("\n", $this->buffer);
			
			// I hope this will not slow down the system.
			array_walk($arrBufLine, array($this, 'trimString'));
			
			$first_line = true;
			$arrHeader = array();
			$arrFields = array();
			foreach ($arrBufLine as $bufLine) {
				$arrField = explode('|', $bufLine);
				if (($first_line) && (is_array($this->arrHeader))) {
					$result = array_combine($this->arrHeader, $arrField);
					if ($result !== false) 
						$arrHeader = $result;
					else
						return null;
					$first_line = false;					
				} else {
					$result = array_combine($this->arrConfig, $arrField);
					if ($result !== false)
						$arrFields[] = $result;
					else 
						return null;
				}
			}
			
			$arrResult = array(
				'header' => $arrHeader,
				'content' => $arrFields
			);
			
			return $arrResult;
		}
		
		private function trimString(&$str) {
			$str = trim($str);
		}
		
		public function __destruct() {
		
		}
	}
	// End of file.